package xcmg.device.service.company;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.company.CompanyInvitationCodeDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.CompanyInvitationCodeMapper;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.infra.CompanyConstants;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.enums.ApplyStatusEnum;
import xcmg.device.infra.enums.CompanyTypeEnum;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.service.basic.DataDictionaryService;
import xcmg.device.service.vo.basic.DataDictionaryVO;
import xcmg.device.service.vo.company.CompanyApplyVO;
import xcmg.device.service.vo.company.CompanyDealerVO;
import xcmg.device.service.vo.company.CompanyInfoVO;
import xcmg.device.service.vo.company.CompanyInvitationInfoVO;
import xcmg.device.service.vo.company.CompanyRegisterVO;
import xcmg.device.service.vo.company.CompanySearchConditionVO;
import xcmg.device.service.vo.company.CompanyShowVO;
import xcmg.device.util.CompanyUtil;
import yb.ecp.fast.dto.WorkSpaceDTO;
import yb.ecp.fast.feign.AuthClient;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.Ref;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sqq on 2017/12/22.
 */

@Service
public class CompanyInfoService {

    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    @Autowired
    private CompanyInvitationCodeMapper companyInvitationCodeMapper;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    @Lazy
    private CompanyDealerService companyDealerService;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private AuthClient authClient;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private CompanyApplyService companyApplyService;

    @Autowired
    private CompanySupplierMapper companySupplierMapper;

    @Autowired
    private CompanyUtil companyUtil;

    /**
     * 新增企业信息，同时增加企业工作空间和默认管理员<br>
     * 默认管理员登录账号为orgId
     *
     * @param companyInfoVO CompanyInfoVO
     * @return ErrorCode
     * @throws Exception Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode insert(CompanyInfoVO companyInfoVO, Ref<String> orgIdRef) throws Exception {
        if (null == companyInfoVO) {
            return ErrorCode.IllegalArument;
        }
        companyInfoVO.setOrgId(null);
        CompanyInfoDO companyInfoDO = companyInfoMapper.checkCompanyExist(getDO(companyInfoVO));
        if (null != companyInfoDO) {
            return ErrorCode.ComSuplierNoOrgcodeDuplicated;
        }
//        CompanyInfoDO sapCodeExist = companyInfoMapper.checkSAPCodeExist(getDO(companyInfoVO));
//        if (null != sapCodeExist) {
//            return ErrorCode.SAPCodeDuplicated;
//        }
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            return ErrorCode.IllegalArument;
        }
        companyInfoVO.setOrgId(textResult.getValue());
        orgIdRef.set(textResult.getValue());
        companyInfoVO.setCreateDate(new Date());
        companyInfoVO.setIsDel(false);
        if (null == companyInfoVO.getChannel()) {
            companyInfoVO.setChannel(0);//管理端添加
        }
        CompanyInfoDO companyInfo4DB = getDO(companyInfoVO);
        companyInfo4DB.setDocumentPre(String.format("%04d", companyInfoMapper.getDocumentPre()));
        int ret = companyInfoMapper.insert(companyInfo4DB);
        if (ret == 0) {
            throw new CommonBusiExceptions("添加企业信息失败！");
        }

        WorkSpaceDTO workSpaceDTO = new WorkSpaceDTO();
        workSpaceDTO.setId(companyInfoVO.getOrgId());
        workSpaceDTO.setName(companyInfoVO.getCompanyName());
        workSpaceDTO.setTempId(companyInfoVO.getModuleTeplateId());
        workSpaceDTO.setAccount(companyInfoVO.getDealerCode());
        ActionResult<?> actionResult = authClient.addWrokSpace(workSpaceDTO);

        if (actionResult.getCode() != 0) {
            throw new CommonBusiExceptions("创建企业工作空间失败！");
        }
        return ErrorCode.Success;
    }

    public CompanyInfoVO info(String orgId) {
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(orgId);

        if (null == companyInfoDO) {
            return null;
        }
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByPlatOrgId(orgId);
        CompanyInfoVO companyInfoVO = getVO(companyInfoDO, null, null);
        if (companyDealerDO == null) {
            companyInfoVO.setDealerLever(-1);
            companyInfoVO.setDealerCode(companyInfoVO.getOrgCode());
        } else {
            CompanyDealerVO cv = BeanUtil.do2bo(companyDealerDO, CompanyDealerVO.class);
            companyInfoVO.setCompanyDealerVO(cv);
            companyInfoVO.setDealerLever(companyDealerDO.getDealerLevel());
            companyInfoVO.setDealerCode(companyDealerDO.getDealerCode());
        }
        return companyInfoVO;
    }


    public List<CompanyInfoVO> infos(List<String> orgIds) {
        if (CollectionUtils.isEmpty(orgIds)) {
            return Collections.emptyList();
        }
        List<CompanyInfoVO> r = new ArrayList<>(orgIds.size());
        List<CompanyInfoDO> ll = companyInfoMapper.items(orgIds);

        if (CollectionUtils.isNotEmpty(ll)) {
            Map<String, String> tmpNameMap = new HashMap<>();
            Map<String, DataDictionaryVO> cpmTypeMap = new HashMap<>();
            ll.forEach(x -> {
                r.add(getVO(x, tmpNameMap, cpmTypeMap));
            });
        }
        return r;
    }


    /**
     * 查询邀请码发送方信息
     *
     * @param invitationCode String
     * @return CompanyInfoVO
     */
    public CompanyInfoVO itemByInvitationCode(String invitationCode) {
        //校验邀请码是否合法
        CompanyInvitationCodeDO inviteInfo = queryInviteInfo(invitationCode);
        if (null == inviteInfo) {
            return null;
        }
        return info(inviteInfo.getSenderOrgId());
    }

    /**
     * 查询所属企业信息
     *
     * @param userId String
     * @return CompanyInfoVO
     * @throws Exception Exception
     */
    public CompanyInfoVO querySelfCompanyInfo(String userId) throws Exception {
        ActionResult<?> actionResult = authClient.queryWorkspaceId(userId);
        if (ErrorCode.Success.getCode() != actionResult.getCode()) {
            return null;
        }
        String orgId = (String) actionResult.getValue();
        return this.info(orgId);
    }

    /**
     * 企业注册<br>
     * 成功，则生成企业申请审核记录，状态为待审核
     *
     * @param companyRegisterVO CompanyRegisterVO
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode register(CompanyRegisterVO companyRegisterVO) {
        //校验邀请码是否合法
        CompanyInvitationCodeDO inviteInfo = queryInviteInfo(companyRegisterVO.getInvitationCode());

        if (null == inviteInfo) {
            return ErrorCode.InvitationCodeFail;
        }

        //校验企业是否已经存在
        CompanyInfoDO companyInfoDO = new CompanyInfoDO(companyRegisterVO.getOrgCode(), companyRegisterVO.getCompanyName());
        CompanyInfoDO companyInfo = companyInfoMapper.checkCompanyExist(companyInfoDO);

        if (null != companyInfo) {
            return ErrorCode.CompanyExist;
        }

        //校验企业审核信息是否存在
        CompanyApplyVO companyApplyVO = companyApplyService.checkApplyRecored(companyRegisterVO);

        ErrorCode checkRet = checkApplyCondition(companyApplyVO);
        if (ErrorCode.Success != checkRet) {
            return checkRet;
        }

        //邀请码置为无效
        inviteInfo.setCodeState(1);
        inviteInfo.setUpdateDate(new Date());
        inviteInfo.setInvitationCode(companyRegisterVO.getInvitationCode());

        int updateRet = companyInvitationCodeMapper.update(inviteInfo);
        if (0 >= updateRet) {
            return ErrorCode.DisableInvitationCodeFail;
        }
        int boundRet = 0;
        if (inviteInfo.getInviteType() == 1) {
            //更新下游企业审核状态（审核中）
            boundRet = companyDealerMapper.updateApplyStatus(inviteInfo.getSenderOrgId(), inviteInfo.getReceiverOrgId(), CompanyConstants.APPLY_STATUS_AUDITING);
        }
        if (inviteInfo.getInviteType() == 2) {
            boundRet = companySupplierMapper.updateApplyStatus(inviteInfo.getSenderOrgId(), inviteInfo.getReceiverOrgId(), CompanyConstants.APPLY_STATUS_AUDITING);
        }

        if (0 >= boundRet) {
            return ErrorCode.RelationCompanyFail;
        }

        if (null == companyApplyVO) {
            return insertApplyRecord(companyRegisterVO, inviteInfo);
        } else {
            return updateApplyRecord(companyRegisterVO, inviteInfo, companyApplyVO);
        }
    }

    /**
     * 更新审核记录
     *
     * @param companyRegisterVO       CompanyRegisterVO 企业注册信息
     * @param companyInvitationCodeDO CompanyInvitationCodeDO 邀请码信息
     * @param companyApplyVO          CompanyApplyVO 已存在的审核记录
     * @return ErrorCode
     */
    public ErrorCode updateApplyRecord(CompanyRegisterVO companyRegisterVO, CompanyInvitationCodeDO companyInvitationCodeDO, CompanyApplyVO companyApplyVO) {
        //添加申请记录
        companyApplyVO.setCompanyName(companyRegisterVO.getCompanyName());
        companyApplyVO.setOrgCode(companyRegisterVO.getOrgCode());
        companyApplyVO.setInvitationCode(companyRegisterVO.getInvitationCode());
        companyApplyVO.setSenderId(companyInvitationCodeDO.getSenderOrgId());
        companyApplyVO.setReceiverId(companyInvitationCodeDO.getReceiverOrgId());
        companyApplyVO.setStatus(ApplyStatusEnum.Saved.getCode());//待审核状态
        return companyApplyService.update(companyApplyVO);
    }

    /**
     * 新增审核记录
     *
     * @param companyRegisterVO       CompanyRegisterVO 企业注册信息
     * @param companyInvitationCodeDO CompanyInvitationCodeDO 邀请码信息
     * @return ErrorCode
     */
    public ErrorCode insertApplyRecord(CompanyRegisterVO companyRegisterVO, CompanyInvitationCodeDO companyInvitationCodeDO) {
        CompanyApplyVO companyApplyVO = new CompanyApplyVO();
        companyApplyVO.setCompanyName(companyRegisterVO.getCompanyName());
        companyApplyVO.setOrgCode(companyRegisterVO.getOrgCode());
        companyApplyVO.setInvitationCode(companyRegisterVO.getInvitationCode());
        companyApplyVO.setSenderId(companyInvitationCodeDO.getSenderOrgId());
        companyApplyVO.setReceiverId(companyInvitationCodeDO.getReceiverOrgId());
        companyApplyVO.setStatus(ApplyStatusEnum.Saved.getCode());//待审核状态
        ErrorCode r = companyApplyService.insert(companyApplyVO);
        companyRegisterVO.setApplyId(companyApplyVO.getId());
        return r;
    }


    /**
     * 校验请求是否合法
     *
     * @param companyApplyVO
     * @return ErrorCode
     */
    private ErrorCode checkApplyCondition(CompanyApplyVO companyApplyVO) {
        if (null == companyApplyVO) {
            return ErrorCode.Success;
        }

        if (ApplyStatusEnum.Saved.getCode().equals(companyApplyVO.getStatus())) {
            return ErrorCode.CompanyAuditNotYet;
        }

        if (ApplyStatusEnum.Pass.getCode().equals(companyApplyVO.getStatus())) {
            return ErrorCode.CompanyAuditPass;
        }

        return ErrorCode.Success;
    }


    /**
     * 查询邀请码信息<br />
     * 邀请码是否在[邀请时间][失效时间]之间
     *
     * @param inviteCode String
     * @return CompanyInvitationCodeDO
     */
    public CompanyInvitationCodeDO queryInviteInfo(String inviteCode) {
        CompanyInvitationCodeDO companyInvitationCodeDO = new CompanyInvitationCodeDO();
        companyInvitationCodeDO.setInvitationCode(inviteCode);

        companyInvitationCodeDO.setCodeState(0);
        companyInvitationCodeDO.setInviteDate(new Date());
        companyInvitationCodeDO.setExpireDate(new Date());
        CompanyInvitationCodeDO inviteInfo = companyInvitationCodeMapper.invitationInfo(companyInvitationCodeDO);

        return inviteInfo;
    }


    public CompanyInvitationInfoVO inviteCompanyInfo(String invitationCode) {
        CompanyInvitationCodeDO inviteInfo = queryInviteInfo(invitationCode);
        if (null == inviteInfo) {
            return null;
        }
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(inviteInfo.getSenderOrgId());
        CompanyInvitationInfoVO companyInvitationInfoVO = new CompanyInvitationInfoVO();
        companyInvitationInfoVO.setCompanyInfo(getVO(companyInfoDO, null, null));
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByOrgId(inviteInfo.getSenderOrgId(), inviteInfo.getReceiverOrgId());
        CompanyDealerVO companyDealerVO = companyDealerService.getVO(companyDealerDO);
        companyInvitationInfoVO.setDealerInfo(companyDealerVO);
        return companyInvitationInfoVO;
    }

    /**
     * 封装DO
     *
     * @param companyInfoVO CompanyInfoVO
     * @return CompanyInfoDO
     */
    private CompanyInfoDO getDO(CompanyInfoVO companyInfoVO) {
        if (null == companyInfoVO) {
            return null;
        }
        CompanyInfoDO companyInfoDO = new CompanyInfoDO();
        companyInfoDO.setOrgId(companyInfoVO.getOrgId());
        companyInfoDO.setOrgCode(companyInfoVO.getOrgCode());
        companyInfoDO.setCompanyName(companyInfoVO.getCompanyName());
        companyInfoDO.setShortName(companyInfoVO.getShortName());
        companyInfoDO.setAddress(companyInfoVO.getAddress());
        companyInfoDO.setCompanyType(companyInfoVO.getCompanyType());
        companyInfoDO.setCompanyClassId(companyInfoVO.getCompanyClassId());
        companyInfoDO.setZip(companyInfoVO.getZip());
        companyInfoDO.setFax(companyInfoVO.getFax());
        companyInfoDO.setContact(companyInfoVO.getContact());
        companyInfoDO.setContactTel(companyInfoVO.getContactTel());
        companyInfoDO.setChannel(companyInfoVO.getChannel());
        companyInfoDO.setCreateDate(companyInfoVO.getCreateDate());
        companyInfoDO.setIsDel(companyInfoVO.getIsDel());
        companyInfoDO.setModuleTeplateId(companyInfoVO.getModuleTeplateId());
        companyInfoDO.setIsSap(companyInfoVO.getIsSap());
        companyInfoDO.setSapCode(companyInfoVO.getSapCode());
        companyInfoDO.setIsBarcode(companyInfoVO.getIsBarcode());
        companyInfoDO.setIsReturnAudit(companyInfoVO.getIsReturnAudit());
        companyInfoDO.setFactoryId(companyInfoVO.getFactoryId());
        companyInfoDO.setFactoryName(companyInfoVO.getFactoryName());
        companyInfoDO.setLoginId(companyInfoVO.getLoginId());
        companyInfoDO.setSupplierNo(companyInfoVO.getSupplierNo());
        return companyInfoDO;
    }

    /**
     * 获取企业信息列表
     *
     * @param condition SearchCommonVO
     * @return PageCommonVO
     * @throws Exception Exception
     */
    public PageCommonVO<CompanyShowVO> list(SearchCommonVO<CompanyInfoVO> condition) throws Exception {
        PageCommonVO<CompanyShowVO> pageCommonVO = new PageCommonVO<CompanyShowVO>();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<CompanyInfoDO> doList = companyInfoMapper.list(condition.getFilters());
        List<CompanyShowVO> voList = new ArrayList<>();
        Map<String, String> tmpNameMap = new HashMap<>();
        Map<String, DataDictionaryVO> cpmTypeMap = new HashMap<>();
        for (CompanyInfoDO companyInfoDO : doList) {
            if (companyInfoDO == null) {
                continue;
            }
            CompanyShowVO companyInfoVO = getVO(companyInfoDO, tmpNameMap, cpmTypeMap);
            companyInfoVO.setTemplateName(this.queryTemplateName(companyInfoVO.getModuleTeplateId(), tmpNameMap));
            voList.add(companyInfoVO);
        }
        pageCommonVO.setPageInfo(new PageInfo<CompanyInfoDO>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * 获取企业信息列表
     *
     * @param condition SearchCommonVO
     * @return PageCommonVO
     * @throws Exception Exception
     */
    public PageCommonVO<CompanyShowVO> listUnBind(SearchCommonVO<CompanySearchConditionVO> condition, String orgId) throws Exception {
        condition.getFilters().setOemOrgId(orgId);
        PageCommonVO<CompanyShowVO> pageCommonVO = new PageCommonVO<CompanyShowVO>();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<CompanyInfoDO> doList = companyInfoMapper.listUnBind(condition.getFilters());
        List<CompanyShowVO> voList = new ArrayList<>();
        Map<String, String> tmpNameMap = new HashMap<>();
        Map<String, DataDictionaryVO> cpmTypeMap = new HashMap<>();
        for (CompanyInfoDO companyInfoDO : doList) {
            if (companyInfoDO == null) {
                continue;
            }
            CompanyShowVO companyInfoVO = getVO(companyInfoDO, tmpNameMap, cpmTypeMap);

            companyInfoVO.setTemplateName(this.queryTemplateName(companyInfoVO.getModuleTeplateId(), tmpNameMap));

            voList.add(companyInfoVO);
        }
        pageCommonVO.setPageInfo(new PageInfo<CompanyInfoDO>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * 导出企业信息
     *
     * @param companyIds List<String>
     * @throws Exception Exception
     */
    public void export(List<String> companyIds) {
        List<CompanyShowVO> companyShowVOs = new ArrayList<>();
        Map<String, String> tmpNameMap = new HashMap<>();
        Map<String, DataDictionaryVO> cpmTypeMap = new HashMap<>();
        for (String companyId : companyIds) {
            CompanyInfoDO companyInfoDO = companyInfoMapper.item(companyId);
            CompanyShowVO companyShowVO = getVO(companyInfoDO, tmpNameMap, cpmTypeMap);
            if (null == companyShowVO) {
                continue;
            }
            companyShowVOs.add(companyShowVO);
        }
        invokeExport(companyShowVOs);
    }

    /**
     * 导出全部企业
     *
     * @param companyInfoVO CompanyInfoVO
     * @throws Exception Exception
     */
    public void exportAll(CompanyInfoVO companyInfoVO) {
//        //PageHelperPlus.startPage(0, 0, "CREATE_DATE desc");
        List<CompanyInfoDO> companyInfoDOs = companyInfoMapper.list(companyInfoVO);
        List<CompanyShowVO> companyShowVOs = new ArrayList<>();
        if (ListUtil.isNullOrEmpty(companyInfoDOs)) {
            invokeExport(companyShowVOs);
            return;
        }
        Map<String, String> tmpNameMap = new HashMap<>();
        Map<String, DataDictionaryVO> cpmTypeMap = new HashMap<>();
        for (CompanyInfoDO companyInfoDO : companyInfoDOs) {
            CompanyShowVO companyShowVO = getVO(companyInfoDO, tmpNameMap, cpmTypeMap);
            if (null == companyShowVO) {
                continue;
            }
            companyShowVOs.add(companyShowVO);
        }
        invokeExport(companyShowVOs);
    }

    /**
     * 查询企业权限模板名称，空则返回空字符串
     *
     * @param tempId String
     * @return String
     * @throws Exception Exception
     */
    private String queryTemplateName(String tempId, Map<String, String> tmpNameMap) throws Exception {
        if (StringUtil.isNullOrEmpty(tempId)) {
            return "";
        }
        if (null != tmpNameMap && tmpNameMap.containsKey(tempId)) {
            return tmpNameMap.get(tempId);
        }
        ActionResult<?> actionResult = authClient.templateById(tempId);
        Map<String, String> template = (Map<String, String>) actionResult.getValue();

        String r = null == template ? "" : template.get("name");
        if (null != tmpNameMap) {
            tmpNameMap.put(tempId, r);
        }
        return r;
    }

    /**
     * 封装VO，并增加模板名称字段
     *
     * @param companyInfoDO CompanyInfoDO
     * @return CompanyShowVO
     */
    private CompanyShowVO getVO(CompanyInfoDO companyInfoDO, Map<String, String> tmpNameMap, Map<String, DataDictionaryVO> cpmTypeMap) {
        if (companyInfoDO == null) {
            return null;
        }
        CompanyShowVO companyInfoVO = new CompanyShowVO();
        companyInfoVO.setOrgId(companyInfoDO.getOrgId());
        companyInfoVO.setOrgCode(companyInfoDO.getOrgCode());
        companyInfoVO.setCompanyName(companyInfoDO.getCompanyName());
        companyInfoVO.setShortName(companyInfoDO.getShortName());
        companyInfoVO.setAddress(companyInfoDO.getAddress());
        companyInfoVO.setCompanyType(companyInfoDO.getCompanyType());
        companyInfoVO.setCompanyClassId(companyInfoDO.getCompanyClassId());
        companyInfoVO.setZip(companyInfoDO.getZip());
        companyInfoVO.setFax(companyInfoDO.getFax());
        companyInfoVO.setContact(companyInfoDO.getContact());
        companyInfoVO.setContactTel(companyInfoDO.getContactTel());
        companyInfoVO.setChannel(companyInfoDO.getChannel());
        companyInfoVO.setCreateDate(companyInfoDO.getCreateDate());
        companyInfoVO.setIsDel(companyInfoDO.getIsDel());
        companyInfoVO.setModuleTeplateId(companyInfoDO.getModuleTeplateId());
        companyInfoVO.setIsSap(companyInfoDO.getIsSap());
        companyInfoVO.setSapCode(companyInfoDO.getSapCode());
        companyInfoVO.setIsBarcode(companyInfoDO.getIsBarcode());
        companyInfoVO.setIsReturnAudit(companyInfoDO.getIsReturnAudit());
        companyInfoVO.setIsUrgentPrice(companyInfoDO.getIsUrgentPrice());
        companyInfoVO.setFactoryId(companyInfoDO.getFactoryId());
        companyInfoVO.setFactoryName(companyInfoDO.getFactoryName());
        companyInfoVO.setSupplierNo(companyInfoDO.getSupplierNo());
        companyInfoVO.setLoginId(companyInfoDO.getLoginId());

        String tempName = "";
        try {
            tempName = queryTemplateName(companyInfoDO.getModuleTeplateId(), tmpNameMap);
        } catch (Exception e) {
            LogHelper.fatal("", e);
        }
        companyInfoVO.setTemplateName(tempName);
        DataDictionaryVO cpmpannyType = null;
        if (null != cpmTypeMap && null != cpmTypeMap.get(String.valueOf(companyInfoDO.getCompanyType()))) {
            cpmpannyType = cpmTypeMap.get(String.valueOf(companyInfoDO.getCompanyType()));
        } else {
            cpmpannyType = dataDictionaryService.itemByCode(CompanyTypeEnum.Type.Name.toString(), String.valueOf(companyInfoDO.getCompanyType()));
            if (null != cpmTypeMap) {
                cpmTypeMap.put(String.valueOf(companyInfoDO.getCompanyType()), cpmpannyType);
            }
        }
        if (null != companyInfoDO.getChannel()) {
            CompanyTypeEnum.Channel channel = CompanyTypeEnum.Channel.getExamType(companyInfoDO.getChannel());
            if (null != channel) {
                companyInfoVO.setChannelDesc(channel.getDesc());
            }
        }
        if (null != cpmpannyType) {
            companyInfoVO.setCompanyTypeDesc(cpmpannyType.getName());
        }

        if (null != companyInfoDO.getIsSap() && companyInfoDO.getIsSap() == 1) {
            companyInfoVO.setIsSapStr("是");
        } else {
            companyInfoVO.setIsSapStr("否");
        }

        if (null != companyInfoDO.getIsBarcode() && companyInfoDO.getIsBarcode() == 1) {
            companyInfoVO.setIsBarcodeStr("是");
        } else {
            companyInfoVO.setIsBarcodeStr("否");
        }
        return companyInfoVO;
    }

    /**
     * 修改企业信息
     *
     * @param companyInfoVO CompanyInfoVO
     * @return ErrorCode
     * @throws Exception Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode update(CompanyInfoVO companyInfoVO) throws Exception {
        if (null == companyInfoVO) {
            return ErrorCode.Success;
        }
        CompanyInfoDO checkDO = companyInfoMapper.checkCompanyExist(getDO(companyInfoVO));
        if (null != checkDO) {
            return ErrorCode.ComSuplierNoOrgcodeDuplicated;
        }
//        CompanyInfoDO sapCodeExist = companyInfoMapper.checkSAPCodeExist(getDO(companyInfoVO));
//        if (null != sapCodeExist) {
//            return ErrorCode.SAPCodeDuplicated;
//        }
        String templateId = companyInfoVO.getModuleTeplateId();
        CompanyInfoVO oldCompanyInfoVO = info(companyInfoVO.getOrgId());
        //更新的权限模板ID与原权限模板不相同，则执行更新权限模板操作
        //同时清除该工作空间下所有角色的权限与菜单配置
        if (!StringUtil.isNullOrEmpty(templateId) && !templateId.equals(oldCompanyInfoVO.getModuleTeplateId())) {
            ActionResult<?> changeResult = authClient.changeTemplate(companyInfoVO.getOrgId(), templateId);
            if (changeResult.getCode() != 0) {
                throw new CommonBusiExceptions("修改企业权限模板失败！");
            }
        }
        CompanyInfoDO companyInfoDO = getDO(companyInfoVO);
        return companyInfoMapper.update(companyInfoDO) > 0 ? ErrorCode.Success : ErrorCode.CompanyUpdateFail;
    }

    public ErrorCode updateInfo(CompanyInfoVO companyInfoVO) {
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(companyInfoVO.getOrgId());
        companyInfoDO.setShortName(companyInfoVO.getShortName());
        companyInfoDO.setAddress(companyInfoVO.getAddress());
        companyInfoDO.setContact(companyInfoVO.getContact());
        companyInfoDO.setContactTel(companyInfoVO.getContactTel());
        companyInfoDO.setFax(companyInfoVO.getFax());
        companyInfoDO.setZip(companyInfoVO.getZip());
        return companyInfoMapper.update(companyInfoDO) > 0 ? ErrorCode.Success : ErrorCode.CompanyOrgIdDuplicated;
    }

    /**
     * 批量删除企业
     *
     * @param orgIds List
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode delete(List<String> orgIds, Ref<List<String>> faildRef) {
        List<String> fail = new ArrayList<>();
        for (String orgId : orgIds) {
            int ret = companyInfoMapper.removeCompany(orgId);
            if (0 >= ret) {
                fail.add(orgId);
            }
            authClient.removeWorkspace(orgId);//更改企业对于的工作空间状态为无效，限制企业下用户无法登陆
        }
        if (!ListUtil.isNullOrEmpty(fail)) {
            faildRef.set(fail);
            return ErrorCode.CompanyDeleteFail;
        }
        return ErrorCode.Success;
    }

    /**
     * 企业信息导出
     *
     * @param voList
     * @throws Exception
     */
    private void invokeExport(List<CompanyShowVO> voList) {
        String title = "企业信息导出";
        String[] rowsName = new String[]{"序号", "企业代码", "企业名称", "组织机构代码",  "供货工厂", "企业类型",
                "渠道", "登录账号", "权限模板"};
        List<Object[]> dataList = new ArrayList<Object[]>();

        if (ListUtil.isNullOrEmpty(voList)) {
            ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
            exportUtil.export(response);
            return;
        }
        Object[] objs;
        for (int i = 0; i < voList.size(); i++) {
            CompanyShowVO e = voList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = e.getSupplierNo();
            objs[2] = e.getCompanyName();
            objs[3] = e.getOrgCode();
            objs[4] = e.getFactoryName();
            objs[5] = e.getCompanyTypeDesc();

            objs[6] = e.getChannelDesc();
            objs[7] = e.getOrgId();
            objs[8] = e.getTemplateName();
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    /**
     * 根据sapCode获取公司信息
     *
     * @param sapCode
     * @return
     */
    public CompanyInfoDO getBySapCode(String sapCode) {
        return companyInfoMapper.itemBySap(sapCode);
    }

    public String getSapCodeByOrgId(String orgId) {
        return companyInfoMapper.getSapCodeByOrgId(orgId);
    }

    public List<CompanyInfoDO> selectBatchByOrgIds(List<String> orgIds) {
        return companyInfoMapper.selectBatchByOrgIds(orgIds);
    }

    public List<CompanyInfoDO> listCoreComs(CompanyInfoVO companyInfoVO) {
        return companyInfoMapper.listCoreComs(companyInfoVO);
    }

    public List<CompanyInfoDO> listCoreComsForCore(CompanyInfoVO companyInfoVO) {
        return companyInfoMapper.listCoreComsForCore(companyInfoVO);
    }

    public CompanyInfoDO getByOrgId(String orgId) {
        if (StringUtils.isEmpty(orgId)) {
            return null;
        }
        CompanyInfoDO result = companyInfoMapper.item(orgId);
        return result;
    }

    public Integer isFirstLevelCompany(String orgId) {
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByPlatOrgId(orgId);
        if (companyDealerDO == null) {
            return 0;
        } else if (companyUtil.ynOrgId().equals(companyDealerDO.getOrgId())) {
            return 1;
        }
        return 0;
    }

    public Map<String, CompanyInfoDO> queryCommpanyInfo(List<String> suplierNos) {
        Map<String, CompanyInfoDO> m = new HashMap<>();
        if (suplierNos == null || suplierNos.size() == 0) {
            List<CompanyInfoDO> list = companyInfoMapper.queryCommpanyInfoBySuplierNos(null);
            if (list == null || list.size() == 0) {
                return m;
            }
            list.forEach(companyInfoDO -> {
                m.put(companyInfoDO.getSupplierNo(), companyInfoDO);
            });
            return m;
        }
        Lists.partition(suplierNos, 1000).forEach(suplierNoList -> {
            List<CompanyInfoDO> list = companyInfoMapper.queryCommpanyInfoBySuplierNos(suplierNoList);
            if (list == null || list.size() == 0) {
                return;
            }
            list.forEach(companyInfoDO -> {
                m.put(companyInfoDO.getSupplierNo(), companyInfoDO);
            });
        });
        return m;
    }
}
